//
//  QXQRCodeMyselfVC.swift
//  QXWeibo
//
//  Created by QinXin on 15/6/29.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

import UIKit
import FFAutoLayout


class QXQRCodeMyselfVC: UIViewController {

    class func create() -> UINavigationController {
        let vc = QXQRCodeMyselfVC()
        let nav = UINavigationController(rootViewController: vc)
        return nav
    }
    
    lazy var QRCodeImageView: UIImageView = UIImageView()
    
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        
        view.addSubview(QRCodeImageView)
        QRCodeImageView.ff_AlignInner(ff_AlignType.CenterCenter, referView: view, size: CGSize(width: 200, height: 200))
        QRCodeImageView.backgroundColor = UIColor.lightGrayColor()
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        QRCodeImageView.image = gennerateQRCodeImage("Labi3285", icon: UIImage(named: "icon00")!)
        
        // 打印系统内置的所有滤镜
//        print(CIFilter.filterNamesInCategory(kCICategoryBuiltIn))
    }
    
    private func gennerateQRCodeImage(dataStr: String, icon: UIImage) -> UIImage {
        
        // MARK: -
        // MARK: 二维码生成
        // 二维码滤镜
        let qrFilter = CIFilter(name: "CIQRCodeGenerator")!
        qrFilter.setDefaults()
        // 设置内容
        qrFilter.setValue(dataStr.dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage")
        // 生成 27 x 27 的 图片
        let ciImage = qrFilter.outputImage
        // 放大图片（变清晰）
        let transform = CGAffineTransformMakeScale(15, 15)
        // 二维码图片生成
        let transformedQrImage = ciImage.imageByApplyingTransform(transform)
        
        
        // MARK: 颜色设置
        // 颜色滤镜
        let colorFilter = CIFilter(name: "CIFalseColor")!
        colorFilter.setDefaults()
        // 设置颜色滤镜的图片
        colorFilter.setValue(transformedQrImage, forKey: "inputImage")
        // 二维码颜色
        colorFilter.setValue(CIColor(color: UIColor.blackColor()), forKey: "inputColor0")
        // 背景颜色
        colorFilter.setValue(CIColor(color: UIColor.whiteColor()), forKey: "inputColor1")
        // 生成颜色渲染后的图片
        let coloredQrImage = UIImage(CIImage: colorFilter.outputImage)
        
        // MARK: 添加中心小图片
        UIGraphicsBeginImageContext(coloredQrImage.size)
        let rect = CGRect(origin: CGPointZero, size: coloredQrImage.size)
        coloredQrImage.drawInRect(rect)
        let wh = rect.width * 0.25
        let x = (rect.width - wh) * 0.5
        let y = (rect.height - wh) * 0.5
        icon.drawInRect(CGRect(x: x, y: y, width: wh, height: wh))
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return resultImage
        
    }

}
